
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;

namespace ScrewTurn.Wiki {

	public partial class GetFile : System.Web.UI.Page {

		protected void Page_Load(object sender, EventArgs e) {
			if(SessionFacade.LoginKey == null && Settings.PrivateAccess) {
				Response.StatusCode = 401;
				Response.Redirect("AccessDenied.aspx");
			}

			if(Request["File"] == null) {
				Response.StatusCode = 404;
				Response.Write(Resources.Messages.FileNotFound);
				return;
			}

			string filename = Settings.UploadDirectory + Request["File"];
			DirectoryInfo info = new DirectoryInfo(Path.GetDirectoryName(filename).TrimEnd('\\'));
			DirectoryInfo up = new DirectoryInfo(Settings.UploadDirectory.TrimEnd('\\'));
			if(!info.FullName.ToLower(CultureInfo.CurrentCulture).StartsWith(up.FullName.ToLower(CultureInfo.CurrentCulture))) {
				Response.StatusCode = 403;
				Response.Write(filename + "<br />");
				Response.Write(Resources.Messages.Forbidden);
				return;
			}
			if(!File.Exists(filename)) {
				Response.StatusCode = 404;
				Response.Write(filename + "<br />");
				Response.Write(Resources.Messages.FileNotFound);
				return;
			}

			string mime = "";
			try {
				string ext = Path.GetExtension(filename);
				if(ext.StartsWith(".")) ext = ext.Substring(1).ToLowerInvariant(); // Remove trailing dot
				mime = GetMimeType(ext);
			}
			catch {
				Response.StatusCode = 404;
				Response.Write(filename + "<br />");
				Response.Write(Resources.Messages.FileNotFound);
				//mime = "application/octet-stream";
				return;
			}

			Response.Clear();
			Response.AddHeader("content-type", mime);
			Response.AddHeader("content-disposition", "inline;filename=\"" + Path.GetFileName(filename) + "\"");

			// Set the cache duration accordingly to the file date/time
			Response.AddFileDependency(filename);
			Response.Cache.SetETagFromFileDependencies();
			Response.Cache.SetLastModifiedFromFileDependencies();
			Response.Cache.SetCacheability(HttpCacheability.Public);
			Response.Cache.SetSlidingExpiration(true);
			Response.Cache.SetValidUntilExpires(true);
			Response.Cache.VaryByParams["File"] = true;

			Response.WriteFile(filename);

		}

		private string GetMimeType(string ext) {
			string mime = "";
			if(MimeTypes.Types.TryGetValue(ext, out mime)) return mime;
			else return "application/octet-stream";
		}

	}

}
